<template>
  <div v-if="isSuper === 0" style="text-align: center; margin-top: 50px;">
    您的权限不够,请联系管理员升级权限。hzshenpeng@corp.netease.com
  </div>
  <div v-else>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <!-- <el-input v-model="searchModel.username" placeholder="用户名" clearable />
          <el-input v-model="searchModel.phone" placeholder="电话" clearable /> -->
          <el-button type="primary" @click="getPaperList" round icon="el-icon-search">查询</el-button>
        </el-col>
        <el-col v-if="isSuper === 1" :span="4" align="right">
          <el-button @click="editPaper(null)" type="primary" icon="el-icon-plus" circle></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 注意事项栏 -->
    <el-card>
      <div slot="header" class="clearfix">
        <h1 class="centered-text">试卷添加注意事项</h1>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="centered-text">
        <div class="center">
          <span class="left-span">基准值为该套试卷各类型题目的考试数量。(当题库和试卷中该科目的题目都少于基准值时</span><br />
          <span class="left-span">开始考试会报错。)</span><br />
          <span class="left-span">举例:飞检试卷基准值m:选择-运维手册为4道,选择-运维技术为2道,填空为6道,简答为2道。</span><br />
          <span class="left-span">1、当每个类型的题目数量n小于等于基准值m时,飞检试卷中n道是固定考试题目,(m-n)道</span><br />
          <span class="left-span">将从总题库中随机抽取。</span><br />
          <span class="left-span">2、当每个类型的题目数量n大于基准值m时,飞检试卷中m道都从n道试题中随机抽取。</span><br />
        </div>
      </div>
    </el-card>


    <!-- 查询结果栏 -->
    <el-card>
      <el-table :data="paper_list" border style="width: 100%">
        <el-table-column label="#" width="100" align="center">
          <template slot-scope="scope">
            {{
              (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="试卷名称" align="center">
        </el-table-column>
        <el-table-column prop="desc" label="试卷详情" align="center">
        </el-table-column>
        <el-table-column prop="fly_exam_type" label="试卷类型" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.fly_exam_type == 3">普通试卷</el-tag>
            <el-tag v-else-if="scope.row.fly_exam_type == 2" type="danger">飞检试卷</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_allow" label="试卷状态" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_allow == 1">开通</el-tag>
            <el-tag v-else type="danger">关闭</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="xz_sc_num" label="选择-运维手册(飞检专属)" align="center">
        </el-table-column>
        <el-table-column prop="xz_js_num" label="选择-运维技术(飞检专属)" align="center">
        </el-table-column>
        <el-table-column prop="xz_num" label="选择"  align="center">
        </el-table-column>
        <el-table-column prop="tk_num" label="填空"  align="center">
        </el-table-column>
        <el-table-column prop="jd_num" label="简答"  align="center">
        </el-table-column> -->
        <el-table-column v-if="isSuper === 1" label="编辑" width="200" align="center">
          <template slot-scope="scope">
            <el-button @click="editPaper(scope.row.id)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
            <el-button @click="open(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[5, 10, 50, 100]" :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 弹出框 -->
    <el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible">
      <!-- <el-dialog :title="title" :visible.sync="dialogFormVisible"> -->
      <el-form :model="paperForm" ref="paperFormRef" :rules="rules">
        <!-- <el-form-item label="科目名称：" prop="paper_name" v-if="paperForm.id == null || paperForm.id == undefined"
          :label-width="formLabelWidth">
          <el-input v-model="paperForm.paper_name" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="试卷名称：" prop="name" :label-width="formLabelWidth">
          <el-input v-model="paperForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="试卷详情：" prop="desc" :label-width="formLabelWidth">
          <el-input v-model="paperForm.desc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="试卷类型：" prop="fly_exam_type" :label-width="formLabelWidth">
          <el-select v-model="paperForm.fly_exam_type" filterable placeholder="选择类型" clearable
            @change="handleSelectFlyExamType">
            <el-option v-for="item in course_type_list" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <template v-if="paperForm.fly_exam_type == 2">
          <el-form-item label="选择-sc(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
            <el-input-number v-model="paperForm.jz_xz_num" controls-position="right" :min="1" :max="20"></el-input-number>
          </el-form-item>
          <el-form-item label="选择-js(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
            <el-input-number v-model="paperForm.jz_xz_js_num" controls-position="right" :min="0"
              :max="20"></el-input-number>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="选择(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
            <el-input-number v-model="paperForm.jz_xz_num" controls-position="right" :min="0" :max="20"></el-input-number>
          </el-form-item>
        </template>


        <el-form-item label="判断(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
          <el-input-number v-model="paperForm.jz_pd_num" controls-position="right" :min="0" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="填空(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
          <el-input-number v-model="paperForm.jz_tk_num" controls-position="right" :min="0" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="简答(基准值)：" :label-width="formLabelWidth" class="custom-input-number">
          <el-input-number v-model="paperForm.jz_jd_num" controls-position="right" :min="0" :max="5"></el-input-number>
        </el-form-item>
        <el-form-item label="随机题目科目：" prop="course_options" :label-width="formLabelWidth">
          <el-select v-model="paperForm.course_options" multiple filterable placeholder="选择科目" clearable
            @change="handleSelectCourse">
            <el-option v-for="item in course_list" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="selectedCourses.length > 0">
          <p>已选科目：</p>
          <el-tag v-for="(course, index) in selectedCourses" :key="index" closable @close="handleTagClose(course)">
            {{ course }}
          </el-tag>
        </div>
        <el-form-item label="试卷状态：" :label-width="formLabelWidth">
          <el-switch v-model="paperForm.is_allow" :active-value="1" :inactive-value="0">
          </el-switch>
        </el-form-item>


        <el-table v-if="paperForm.id != null || paperForm.id != undefined" :data="one_paper_list" border
          style="width: 100%">
          <template v-if="paperForm.fly_exam_type == 2">
            <el-table-column prop="xz_sc_num" label="选择-运维手册" align="center">
            </el-table-column>
            <el-table-column prop="xz_js_num" label="选择-运维技术" align="center">
            </el-table-column>
          </template>
          <template v-else>
            <el-table-column prop="xz_num" label="选择" align="center">
            </el-table-column>
          </template>

          <el-table-column prop="pd_num" label="判断" align="center">
          </el-table-column>
          <el-table-column prop="tk_num" label="填空" align="center">
          </el-table-column>
          <el-table-column prop="jd_num" label="简答" align="center">
          </el-table-column>
        </el-table>

        <el-card v-if="fpdFormVisible == true">
          <el-form-item label="科目名称:" prop="course_name" :label-width="formLabelWidth">
            <el-select v-model="fpdForm.course_id" :key="fpdForm.course_id" filterable placeholder="科目名称" clearable
              @change="handleSelectChange()" @clear="handleClear">
              <el-option v-for=" item  in  course_list " :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="试题类型:" prop="question_type" :label-width="formLabelWidth">
            <el-select v-model="fpdForm.question_type" :key="fpdForm.question_type" filterable placeholder="试题类型"
              clearable @change="handleSelectChange()" @clear="handleClear">
              <el-option v-for=" item  in  question_type_list " :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="试题ID:" prop="question_id" :label-width="formLabelWidth">
            <el-select v-model="fpdForm.question_id" filterable placeholder="试题ID"
              @change="handleSelectChangeById(fpdForm.question_id)">
              <el-option v-for=" item  in question_id_list " :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="试题题目：" prop="content" :label-width="formLabelWidth">
            <!-- <el-input v-model="fpdForm.content" autocomplete="off"></el-input> -->
            <textarea v-model="fpdForm.content" autocomplete="off" rows="3" class="custom-width" readonly></textarea>
          </el-form-item>

          <div style="text-align: center;">
            <el-button @click="logoutFpd">退出</el-button>
            <el-button @click="addFpd" type="primary">添加</el-button>
          </div>
        </el-card>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button v-if="paperForm.id != null || paperForm.id != undefined" @click="showFpd" type="primary"
          style="text-align: center;">添加试题</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="addPaper" type="primary">确 定</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import testApi from "@/api/testMange";
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      rules: {
        name: [
          { required: true, message: "请输入试卷名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        desc: [
          { required: true, message: "请输入详情", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        fly_exam_type: [
          { required: true, message: "请输入试卷类型", trigger: "blur" },
          {
            type: "integer",
            trigger: "blur",
          },
        ],
        course_options: [
          { type: 'array', required: true, message: '请选择随机题目科目', trigger: 'blur' },
          // 其他可能的验证规则...
        ],
      },
      paperForm: {
        // "idc_name": "",
        "is_allow": 1,
      },
      fpdForm: {

      },
      formLabelWidth: "130px",
      fpdFormVisible: false,
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      selectedCourses: [], // 存储已选科目
      course_type_list: [],
      userList: [],
      one_paper_list: [],
      paper_list: [],
      course_list: [],
      question_id_list: [],
      question_type_list: [
        {
          value: 'xz',
          label: '单选'
        }, {
          value: 'mxz',
          label: '多选'
        }, {
          value: 'tk',
          label: '填空'
        }, {
          value: 'jd',
          label: '简答'
        }, {
          value: 'pd',
          label: '判断'
        }
      ]
    };
  },
  methods: {
    handleSelectFlyExamType() {
      // console.log(this.paperForm.fly_exam_type)
      if (this.paperForm.fly_exam_type == 2) {
        this.paperForm.course_options = [1, 4]
      } else {
        this.paperForm.course_options = []
      }
      this.handleSelectCourse();
    },
    handleSelectCourse() {
      // 在用户与表单交互时更新已选科目列表
      this.selectedCourses = this.paperForm.course_options.map(option => {
        const selectedOption = this.course_list.find(course => course.value === option);
        return selectedOption ? selectedOption.label : '';
      });
      // console.log(this.selectedCourses)
    },
    handleTagClose(course) {
      // 处理关闭标签的逻辑，从已选科目列表中移除
      const index = this.selectedCourses.indexOf(course);
      if (index !== -1) {
        this.selectedCourses.splice(index, 1);
      }
    },

    handleSelectChange() {
      // This method will be called when the value in el-select changes
      // You can perform your desired actions here
      // console.log('Selected value:', this.fpdForm.course_id);
      // Call your click method or perform other actions as needed
      this.getQuestionId();
      if (this.fpdForm.question_id != undefined) {
        this.fpdForm.question_id = "";
      }
      this.fpdForm.content = "";
    },
    getQuestionId() {
      // Your click method logic goes here
      // console.log('Click method triggered!');
      testApi.getQuestionList(this.fpdForm).then((response) => {
        this.question_id_list = response.data.api_question_id_list;
      });
    },
    handleClear() {
      this.fpdForm.content = "";
    },
    logoutFpd() {
      this.fpdFormVisible = false;
      this.fpdForm = {};
    },
    async handleSelectChangeById(id) {
      await this.getQuestionById(id);
      // this.fpdForm.course_id = this.course_id;
      // this.fpdForm.question_type = this.question_type;
      this.$forceUpdate();
    },
    async getQuestionById(id) {
      try {
        const response = await testApi.getQuestionById(id);
        this.fpdForm.course_id = response.data.course_id;
        this.fpdForm.question_type = response.data.questionType;
        this.fpdForm.content = response.data.content;
      } catch (error) {
        console.error('Error fetching question by ID:', error);
      }
    },
    showFpd() {
      this.fpdFormVisible = true;
      // this.dialogFormVisible = false;
      this.fpdForm.paper_name_id = this.paperForm.id
      // this.fpdForm.question_id = 1;
    },
    addFpd() {
      testApi.saveFpd(this.fpdForm).then((response) => {
        // 提示提交成功
        this.$message({
          message: response.message,
          type: "success",
        });
        // 刷新页面
        this.editPaper(this.paperForm.id);
      });
    },
    open(Paper) {
      this.$confirm(`您是否确认删除试卷:${Paper.name}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          testApi.deletePaperById(Paper.id).then((response) => {
            this.$message({
              type: "success",
              message: response.message,
            });
            this.getPaperList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addPaper() {
      // 表单验证
      this.$refs.paperFormRef.validate((valid) => {
        if (valid) {
          testApi.savePaper(this.paperForm).then((reponse) => {
            // 关闭弹窗
            this.dialogFormVisible = false;
            // 提示提交成功
            this.$message({
              message: reponse.message,
              type: "success",
            });
            // 刷新页面
            this.getPaperList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    clearForm() {
      this.paperForm = {
        // "idc_name": "",
        // "is_active": 0,
      };
      this.fpdForm = {

      };
      this.fpdFormVisible = false;
      this.$refs.paperFormRef.clearValidate();
      this.getPaperList();
      this.selectedCourses = [];
    },
    editPaper(id) {
      if (id == null) {
        this.title = "新增试卷";
      } else {
        this.title = "修改试卷";
        //先从后端获取user信息
        testApi.getPaperById(id).then((reponse) => {
          this.paperForm = reponse.data;
          this.one_paper_list = reponse.data.fly_exam_question_num_list;
          this.handleSelectCourse();
        });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getPaperList();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getPaperList();
    },
    getPaperList() {
      testApi.getPaperList(this.searchModel).then((response) => {
        this.total = response.data.total;
        this.paper_list = response.data.exam_title;
        this.course_list = response.data.api_course_list;
        this.question_id_list = response.data.api_question_id_list;
        this.course_type_list = response.data.api_fly_exam_type_list;
      });
    },
  },
  created() {
    this.getPaperList();
  },
  computed: {
    ...mapGetters([
      // 'name',
      'isSuper',
      // 'nick_name'
    ]),
  }
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}

.el-dialog .el-input {
  width: 88%;
}

.centered-text {
  text-align: center;
  /* display: block; */
}

.center {
  display: inline-block;
  text-align: left;
}

.left-span {
  /* text-align: left; */
  display: block;
}

.custom-input-number .el-input-number__increase,
.custom-input-number .el-input-number__decrease {
  margin-right: 22px !important;
  /* 调整按钮位置 */
}

.custom-input-number .el-input-number__increase::before,
.custom-input-number .el-input-number__decrease::before {
  border-width: 2px !important;
  /* 调整按钮边框宽度 */
}

.custom-width {
  width: 88%;
  /* 或者其他你想要的宽度值 */
}
</style>